﻿using System;
using System.Collections.ObjectModel;

using Sunyi.Project.WebPoint.DataAccessController;
using Sunyi.Project.WebPoint.DataContract;

namespace Sunyi.Project.WebPoint.BusinessLogic
{
    public partial class PermissionManager
    {
        public bool HasPermission(string pageUrl, string userName, PermissionType permissionType)
        {
            UserDaoController userDaoController = new UserDaoController();
            User user = userDaoController.SelectByName(userName);

            return HasPermission(pageUrl, user, permissionType);
        }

        public bool HasPermission(string pageUrl, User user, PermissionType permissionType)
        {
            bool flag = false;

            if (user == null) return false;

            PageDaoController pageDaoController = new PageDaoController();
            Page page = pageDaoController.SelectByUrl(pageUrl);
            if (page == null || !page.IsActive) return false;

            Permission permission = controller.SelectByName(permissionType.ToString());
            if (permission == null) return false;

            foreach (var roleId in user.Roles)
            {
                flag = HasPermission(page.Id, roleId, permission.Id);

                if (flag) break;
            }

            return flag;
        }

        private bool HasPermission(Guid pageId, Guid roleId, Guid permissionId)
        {
            bool flag = false;

            RoleManager roleManager = new RoleManager();
            Role role = roleManager.Select(roleId);
            if (role == null) return false;

            if (role.Permissions.ContainsKey(pageId) && role.Permissions[pageId] != null)
            {
                flag = role.Permissions[pageId].Contains(permissionId);
            }

            return flag;
        }

        public Collection<Permission> SelectAll()
        {
            return controller.SelectAll();
        }
    }
}
